package com.example.zhihuigongdi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.zhihuigongdi.commer.CommonException;
import com.example.zhihuigongdi.entity.DTO.LoginFormDTO;
import com.example.zhihuigongdi.entity.User;
import com.example.zhihuigongdi.entity.respon.Result;
import com.example.zhihuigongdi.mapper.UserMapper;
import com.example.zhihuigongdi.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhihuigongdi.utils.CheckUtil;
import com.example.zhihuigongdi.utils.JwtUtil;
import com.example.zhihuigongdi.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuhongbin
 * @since 2024-04-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisCache redisCache;

    public Result login(LoginFormDTO loginFormDTO) {
        if (loginFormDTO.getAccount() == null || loginFormDTO.getPassword() == null || loginFormDTO == null) {
            return Result.error("用户传入数据为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("account", loginFormDTO.getAccount());
        User user = this.getOne(queryWrapper);

        if (user == null) {
            throw new CommonException("用户不存在");
        }

        if (!new BCryptPasswordEncoder().matches(loginFormDTO.getPassword(), user.getPassword())) {
            //不能只说密码错误
            throw new CommonException("账号或密码错误");
        }
        String userid = user.getId().toString();
        String token = JwtUtil.createJWT(userid);

        redisCache.setCacheObject("login:" + userid, user);

        return Result.success(token, "登陆成功");
    }

    @Autowired
    private CheckUtil checkUtil;
    @Override
    public Result getMe() {
        User user = checkUtil.getUser();
        checkUtil.checkUser(user);

        return Result.success(user);
    }
}
